package com.video.netty.commons.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qf.entity.RunLogEntity;
import com.video.commons.runtimelog.RequestIdThreadLocal;
import com.video.commons.runtimelog.RunLogUtil;
import io.netty.channel.Channel;
import lombok.Data;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Data
public class ChannelUtil {

    private Channel channel;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息到golang服务器
     */
    public void sendMsg(String msg){

        String idStr = null;
        try {
            JSONObject jsonObject = JSON.parseObject(msg);
            idStr = jsonObject.getString("id");
        } catch (Exception e) {
        }

        RunLogUtil.warn("发送消息到Golang服务 [ send msg ]：[" + idStr + "] --> " + msg);

        String id = RequestIdThreadLocal.getId();
        //记录发送消息的运行日志
        RunLogEntity runLogEntity = new RunLogEntity()
                .setRequestId(id)
                .setUrl("Send:发送给Golang的消息")
                .setClassName(msg)
                .setOrder(RequestIdThreadLocal.getNumber());
        RunLogUtil.runLog(rabbitTemplate, runLogEntity);

        if(channel != null && channel.isActive()) {
            channel.writeAndFlush(msg);
        } else {
            RunLogUtil.info("golang连接可能已经关闭，消息发送失败......");
        }
    }

    /**
     * 发送Map集合的消息
     * @param map
     */
    public void sendMsg(Map map){
        sendMsg(JSONObject.toJSONString(map));
    }

    /**
     * 关闭连接
     */
    public void close(){
        if (isConnection()){
            System.out.println("主动关闭服务器连接......");
            channel.close();
        } else {
            System.out.println("golang服务器未连接成功.....");
        }
    }

    /**
     * 获得连接状态
     * @return
     */
    public boolean isConnection(){
        if (channel != null && channel.isOpen()){
            return true;
        } else {
            return false;
        }
    }
}
